import socket
import threading

def create_server_socket(host, port):
    socket_server = socket.socket();
    socket_server.bind((host, port))
    socket_server.listen()
    print(f"服务端正在监听，地址：端口={host}:{port}")
    print(f"正在等待客户连接……")

    #开启多线程，收发来自多个客户端的数据
    num = 0
    while True:
        num += 1
        conn, addr = socket_server.accept()
        print(f"服务端接收到客户端{num}号的连接请求，客户端信息：{addr}")
        client_handler = threading.Thread(target=handle_client,args=(conn,addr,num))
        client_handler.start()


def handle_client(conn, addr,num):
    while True:
        request = conn.recv(1024).decode("utf-8")
        print(f"客户端,第{num}号:{addr}发来的消息,内容是:{request}")
        # 发送消息到客户端
        msg = input(f"请输入你要回复客户端{num}号，地址:{addr}的内容：")
        if msg == "exit":
            break
        conn.send(msg.encode("utf-8"))
    conn.close()

if __name__ == '__main__':
    #采用固定ip和端口测试
    create_server_socket("127.0.0.1", 8888)
